<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Service\Common\PhoneSms;


use Admin\Data\Common;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Laminas\Json\Json;

class AliSms
{
    private $sendSms;
    private $sendSmsQuery;

    /**
     * 设置短信
     * @param $smsConfig
     * @throws ClientException
     */
    public function setSmsConfig($smsConfig)
    {
        if (!empty($smsConfig['sms_id']) && !empty($smsConfig['sms_secret']) && !empty($smsConfig['sms_sign_name'])) {
            AlibabaCloud::accessKeyClient($smsConfig['sms_id'], $smsConfig['sms_secret'])->regionId('cn-hangzhou')->asDefaultClient();
            $this->sendSms = AlibabaCloud::rpc()->product('Dysmsapi')->version('2017-05-25')->action('SendSms')->method('POST')->host('dysmsapi.aliyuncs.com');
            $this->sendSmsQuery = ['RegionId' => 'cn-hangzhou', 'SignName' => $smsConfig['sms_sign_name']];
        }
    }

    /**
     * 发送短信
     * @param array $data
     * @return bool
     */
    public function sendPhoneSms(array $data)
    {
        if (empty($this->sendSmsQuery)) return false;

        try {
            $this->sendSmsQuery = array_merge($this->sendSmsQuery, ['PhoneNumbers' => implode(',', $this->getPhoneNumbers($data['phone'])), 'TemplateCode' => $data['templateCode'], 'TemplateParam' => Json::encode($this->createSmsContent($data['contentArray']))]);
            return $this->sendSms->options(['query' => $this->sendSmsQuery])->request();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
        return false;
    }

    /**
     * 发送订单短信
     * @param array $data
     * @return bool
     */
    public function sendOrderPhoneSms(array $data)
    {
        if (empty($this->sendSmsQuery)) return false;

        try {
            $this->sendSmsQuery = array_merge($this->sendSmsQuery, ['PhoneNumbers' => implode(',', $this->getPhoneNumbers($data['phone'])), 'TemplateCode' => $data['templateCode'], 'TemplateParam' => Json::encode($this->createOrderSmsContent($data['contentArray']))]);
            return $this->sendSms->options(['query' => $this->sendSmsQuery])->request();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
        return false;
    }

    /**
     * 获取发送电话号码
     * @param $phoneData
     * @return array
     */
    private function getPhoneNumbers($phoneData)
    {
        $phoneArea      = Common::configValue('list', 'phoneArea');
        $phoneNumbers   = [];
        foreach ($phoneData as $value) {
            if($value['areaCode'] == 'CN') $phoneNumbers[] = $value['number'];
            else $phoneNumbers[] = $phoneArea[$value['areaCode']]['areaPhoneCode'].$value['number'];
        }

        return $phoneNumbers;
    }

    /**
     * 对短信内容进行解析
     * @param $data
     * @return array|string[]
     */
    private function createSmsContent($data)
    {
        $contentArray = [
            'code'              => $data['phoneCaptcha'] ?? '',//手机验证码

            'userName'          => $data['userName'] ?? '',         //客户名称
            'changeTime'        => $data['changeTime'] ?? '',       //变动时间
            'changeAmountType'  => $data['changeAmountType'] ?? '', //变动类型
            'changeUserAmount'  => $data['changeUserAmount'] ?? '', //变动金额
            'userAmount'        => $data['userAmount'] ?? '',       //变动后总额
        ];

        return array_filter($contentArray);
    }

    /**
     * 对订单提醒的短信内容进行解析
     * @param $data
     * @return array|string[]
     */
    private function createOrderSmsContent($data)
    {
        $contentArray = [
            'buyName'           => $data['buyName'] ?? '',          //买家名称,
            'orderSn'           => $data['orderSn'] ?? '',          //订单编号
            'orderTotal'        => $data['orderTotal'] ?? '',       //订单金额
            'deliveryName'      => $data['deliveryName'] ?? '',     //快递名称
            'expressNumber'     => $data['expressNumber'] ?? '',    //快递单号
        ];

        return array_filter($contentArray);

    }
}